import { trigger } from "../effect/trigger"
import { hasChanged, TriggerOpTypes } from "../utils"

export default function setHandler(target: any, key: string | symbol, value: any, receiver: any) {
  const type = Object.prototype.hasOwnProperty.call(target, key) ? TriggerOpTypes.SET : TriggerOpTypes.ADD  
  const oldLen = Array.isArray(target) ? target.length : 0
  const oldValue = target[key]
  const res = Reflect.set(target, key, value, receiver)

  // 如果变化，则派发更新
  if(hasChanged(oldValue, value)) {
    // trigger
    trigger(target, type, key)
    // 判断是否是数组，length属性是否有变化
    if (Array.isArray(target) && target.length !== oldLen) {
      if(key !== 'length') {
        trigger(target, TriggerOpTypes.SET, 'length')
      } else {
        // 如果length变小，触发删除操作
        for (let i = target.length; i < oldLen; i++){
          trigger(target, TriggerOpTypes.DELETE, i + '')
        }
      }
    }
  }

  return res
}